<template>
  <view class="width95 margin-center">
    <!-- 动态渲染订单列表 -->
    <view
        v-for="order in orders"
        :key="order.id"
        class="bg-color-white padding-20 border-radius-15 margin-top-30"
    >
      <view class="d-row d-jc-between d-ai-centen padding-10 padding-bottom-20 border-bottom-2">
        订单号：{{ order.number }}
        <!--        <text class="small-font">请根据订单号取餐</text>-->

        <!-- 订单状态 -->
        <view class="d-clo d-ai-end">
          <view
              :class="['padding-bottom-20', 'status-' + order.status]"
          >{{ getOrderStatus(order) }}
          </view>
          <view v-if="order.remainingTime">
            <label>剩余 <label class="colorBlue padding-left-10">{{ order.remainingTime }}</label></label>
          </view>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="d-row d-jc-between padding-10 padding-bottom-20 border-bottom-2">
        <!-- 商品图片 -->
        <scroll-view
            class="scroll-container"
            scroll-x
            enable-flex
            style="white-space: nowrap;"
        >
          <view
              class="scroll-content d-row"
              style="display: flex; flex-wrap: nowrap;"
          >
            <view
                v-for="(detail, index) in order.orderDetailList"
                :key="index"
                class="item-container"
                style="display: inline-block; margin-right: 10rpx;"
            >
              <image
                  :src="detail.image"
                  style="width: 80rpx;height: 80rpx;"
                  class="border-radius-5"
              />
              <view
                  class="d-clo d-jc-between padding-left-0"
                  style="font-size: 23rpx;"
              >
                {{ detail.name }} * {{ detail.number }}
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- 商品详情 -->
        <view class="d-row d-jc-between d-ai-centen padding-10 font30 padding-bottom-10">
          <view>￥ <label class="font-bold font36">{{ order.amount }}元</label></view>
        </view>
      </view>


      <view class="merchant-id">窗口：{{ merchantNames[order.merchantId] || '加载中...' }}</view>
      <!-- 操作按钮 -->
      <view
          class="relative d-row d-ai-center padding-10 padding-top-30"
          v-if="showPayButton(order)"
      >
        <button
            class="absolute right-0"
            plain
            type="primary"
            size="mini"
            @tap="handlePay(order)"
        >
          去支付
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      statusMap: {
        '1': '待付款',
        '2': '待接单',
        '3': '已接单',
        '4': '待取餐',
        '5': '已完成',
        '6': '已取消',
        '7': '退款'
      },
      orders: [],
      merchantNames: {}
    }
  },
  onLoad() {
    this.fetchHistoryOrders();
  },
  methods: {
    // 获取订单状态（示例逻辑）
    getOrderStatus(order) {
      // 根据实际数据字段调整，例如根据status字段
      return this.statusMap[order.status] || '无效订单';
    },
    // 处理支付按钮显示逻辑
    showPayButton(order) {
      return Number(order.status) === 1;
    },
    // 支付操作
    handlePay(order) {
      uni.navigateTo({
        url: `../store/pay?orderNumber=${order.number}`,
        animationType: 'pop-in',
        animationDuration: 2000
      });
    },
    go(type) {
      if ('one' == type) {
        console.log("one--------")
        uni.navigateTo({
          url: '../store/index',
          animationType: 'pop-in',
          animationDuration: 2000
        })
      } else if ('pay' == type) {
        console.log("pay--------")
        uni.navigateTo({
          url: '../store/pay',
          animationType: 'pop-in',
          animationDuration: 2000
        })
      }
    },
    // 获取当前用户的订单列表
    async fetchHistoryOrders() {
      // 从localStorage获取用户ID
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const userId = userInfo.data?.id || 0;
      const page = 1;
      const pageSize = 100;
      if (!userId) {
        uni.showToast({title: '未获取到用户信息', icon: 'none'});
        return;
      }

      // 发起GET请求
      uni.request({
        url: 'http://localhost:8080/order/user/order/historyOrders',
        method: 'GET',
        data: {
          userId, page, pageSize
        },
        success: (res) => {
          if (res.data.code === 0) {
            console.log('dingdanliebioa', res.data.data.records)
            this.orders = res.data.data.records;
            console.log('订单列表更新:', this.orders);
            // 收集商户ID并请求名称
            const merchantIds = [...new Set(this.orders.map(order => order.merchantId))];
            merchantIds.forEach(id => this.fetchMerchantName(id));

          } else {
            uni.showToast({title: '获取订单失败', icon: 'none'});
          }
        },
        fail: () => {
          uni.showToast({title: '网络请求失败', icon: 'none'});
        }
      });
    },
    // 获取商户位置
    async fetchMerchantName(merchantId) {
      try {
        const res = await uni.request({
          url: 'http://localhost:8080/user/user/user/getMerchant',
          method: 'GET',
          data: {merchantId} // 确保参数名正确
        });

        // 调试：输出响应数据
        console.log('响应数据:', res[1]);

        if (res[1].data.code === 0) {
          const {deptName, userName} = res[1].data.data;
          if (deptName && userName) {
            this.$set(this.merchantNames, merchantId, deptName + ' ' + userName);
            console.log('更新后的merchantNames:', this.merchantNames);
          } else {
            console.error('商户名称字段缺失:', res[1]);
          }
        } else {
          console.error('接口返回错误:', res[1].msg);
        }
      } catch (error) {
        console.error('获取商户名称失败:', error);
      }
    }
  }
}
</script>

<style>
uni-page-head, uni-page, page {
  background-color: #f7f7f7;
}

.bgColor {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #bbbbf3;
  z-index: -1;
}

/* 在<style>中添加 */
.scroll-container {
  width: 70%;
  overflow: hidden;
}

.scroll-content {
  display: flex;
  flex-wrap: nowrap;
  white-space: nowrap;
}

.item-container {
  display: inline-block;
  //margin-right: 10rpx;
}

.small-font {
  font-size: 20rpx; /* 根据需求调整数值 */
}

/* 在<style>中添加 */
.status-1 {
  color: #FF9900;
}

/* 待付款：橙色 */
.status-2 {
  color: #FF6666;
}

/* 待接单：红色 */
.status-3 {
  color: #0099FF;
}

/* 已接单：蓝色 */
.status-4 {
  color: #00CC66;
}

/* 派送中：绿色 */
.status-5 {
  color: #339933;
}

/* 已完成：深绿 */
.status-6, .status-7 {
  color: #999;
}

/* 已取消/退款：灰色 */
.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.right-0 {
  right: 0;
}

uni-button[size=mini] {
  display: inline-block;
  line-height: 2.3;
  font-size: 13px;
  padding: 0 1.34em;
  margin-top: -29px;
}


</style>
